import https from "https"
import { assign } from "../utils/index.js"
export class Service {
    constructor() {}
    request(options) {
        return new Promise((resolve, resject) => {
            let opts = assign({}, options, {})
            let raw = "";
            let req = https.request(opts, res => {
                res.on('data', chunk => { raw += chunk })
                res.on('end', () => {
                    try {
                        resolve({ flag: true, data: JSON.parse(raw) })
                    } catch (err) {
                        resject({ flag: false, msg: err.message })
                    }
                })
            }).on('error', (e) => {
                resject({ flag: false, msg: e.message })
            })
            req.end()
        })

    }
}


function singleton(fn) {
    let instance
    return function() {
        return instance || (instance = fn.apply(null, arguments))
    }
}

export const agent = singleton(() => {
    return new Service()
})